﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace InSys.Documents
{
    public partial class UserControlSelectUser : UserControl
    {
        private bool isEmptyUserList;
        private MapTestLinqDataContext db = new MapTestLinqDataContext();
        private int id_user = 0;
        private int id_department = 0;
        private string name_user;
        private string name_department;
        private DateTime actual_date = DateTime.Now;

        private bool IsRefresh = false;

        public AccessUserLoginInfo info;

        public bool IsEmptyUserList { get { return isEmptyUserList; } }

        public int IdUser 
        { 
            get 
            {
                return id_user; 
            }
            set
            {
                id_user = value;
            }
        }
        public int IdDepartment { 
            get 
            { 
                return id_department; 
            }
            set
            {
                id_department = value;
            }
        }
        public string NameUser { get { return name_user; } }
        public string NameDepartment { get { return name_department; } }
        public DateTime ActualDate { get { return actual_date; } set { actual_date = value; selectDepartment(departmentListBox.SelectedValue == null ? 0 : (int)departmentListBox.SelectedValue); } }

        public delegate void UserControlSelectUserEventHandler(object sender, EventArgs e);
        public event UserControlSelectUserEventHandler UserControlSelectUserEvent;
        public void ActivateUser()
        {
            if (null == UserControlSelectUserEvent) return;
            EventArgs e = new EventArgs();
            UserControlSelectUserEvent(this, e);
        }


        public UserControlSelectUser()
        {
            InitializeComponent();
            info = new AccessUserLoginInfo();
            isEmptyUserList = false;
        }

        /// <summary>
        /// Установить дату актуальности
        /// </summary>
        /// <param name="date"></param>
        public UserControlSelectUser(DateTime date) : this()
        {
            actual_date = date;
        }

        /// <summary>
        /// Обновить информацию об отделах и сотрудниках
        /// </summary>
        public void RefreshData()
        {
            int old_id_user = id_user;
            IsRefresh = true;
            try
            {
                IEnumerable<department> queryDepartments = info.getDepartments(); //from item in db.departments orderby item.name select item;
                departmentBindingSource.DataSource = queryDepartments;
                userBindingSource.DataSource = null;
                try
                {
                    if (0 != id_department)
                    {
                        departmentListBox.SelectedValue = id_department;//(from item in db.departments where item.id_department == id_department select item).FirstOrDefault();
                    }
                    else
                    {
                        id_department = (int)departmentListBox.SelectedValue;
                    }
                }
                catch (Exception)
                {
                    id_department = 0;
                }
                selectDepartment(departmentListBox.SelectedValue == null ? 0 : (int)departmentListBox.SelectedValue);
                try
                {
                    if (0 != old_id_user)
                    {
                        userListBox.SelectedValue = old_id_user; // (from item in db.persons where item.id_person == id_user select item).FirstOrDefault();
                        id_user = old_id_user;
                    }
                    else
                    {
                        id_user = (int)userListBox.SelectedValue;
                    }
                }
                catch (Exception)
                {
                    id_user = 0;
                }
            }
            catch (Exception)
            {
                MessageBox.Show(Properties.Resources.LoginError);
            }
            if ((userBindingSource.DataSource as IEnumerable<person>).Count() == 0 && (departmentBindingSource.DataSource as IEnumerable<department>).Count() == 0)
                isEmptyUserList = true;
            IsRefresh = false;
        }

        private void UserControlSelectUser_Load(object sender, EventArgs e)
        {
            try
            {
                if (!db.DatabaseExists())
                {
                    db.CreateDatabase();
                }
                RefreshData();
            }
            catch (Exception)
            {
                MessageBox.Show("Ошибка открытия/создания базы данных. Продолжение работы невозможно.");
                Application.Exit();
            }
        }

        /// <summary>
        /// Осуществить действия при указании номера отдела
        /// </summary>
        /// <param name="value"></param>
        private void selectDepartment(int value)
        {
            userBindingSource.DataSource = null;
            var queryUsers = info.getListPersonsDepartment(value, actual_date);
            userBindingSource.DataSource = queryUsers;
            id_department = value;
            name_department = departmentListBox.SelectedItem == null ? "" : (departmentListBox.SelectedItem as department).name;
            if (false == IsRefresh)
            {
                try
                {
                    userListBox.SelectedIndex = 0;
                    id_user = (int)userListBox.SelectedValue;
                }
                catch (Exception)
                {
                }
            }
        }

        /// <summary>
        /// Осуществить действия при выборе сотрудника
        /// </summary>
        /// <param name="value"></param>
        private void selectUser(int value)
        {
            id_user = value;
            name_user = userListBox.SelectedItem == null ? "" : (userListBox.SelectedItem as person).name;
        }

        private void departmentListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int value = departmentListBox.SelectedValue == null ? 0 : (int)departmentListBox.SelectedValue;
            selectDepartment(value);
        }

        private void userListBox_SelectedIndexChanged(object sender, EventArgs e)
        {

            selectUser(userListBox.SelectedValue == null ? 0 : (int)userListBox.SelectedValue);
         }

        private void userListBox_DoubleClick(object sender, EventArgs e)
        {
            ActivateUser();
        }


    }
}
